const userModel = require('../lib/mysql.js')
const moment = require('moment')
const md = require('markdown-it')();
/**
 * 重置到文章页
 */
exports.getRedirectPosts = async ctx => {
    ctx.redirect('/posts')
}
/**
 * 文章页
 */
exports.getPosts = async ctx => {
    let res,
        postCount,
        name = decodeURIComponent(ctx.request.querystring.split('=')[1]);
    if (ctx.request.querystring) {
        await userModel.findPostCountByName(name)
            .then(result => {
                postCount = result[0].count
            })
        await userModel.findPostByUserPage(name, 1)
            .then(result => {
                res = result
            })
        await ctx.render('selfPosts', {
            session: ctx.session,
            posts: res,
            postsPageLength: Math.ceil(postCount / 10),
        })
    } else {
        await userModel.findPostByPage(1)
            .then(result => {
                res = result
            })
        await userModel.findAllPostCount()
            .then(result => {
                postCount = result[0].count
            })
        await ctx.render('posts', {
            session: ctx.session,
            posts: res,
            postsLength: postCount,
            postsPageLength: Math.ceil(postCount / 10),

        })
    }
}
/**
 * 首页分页， 每次输出10条
 */
exports.postPostsPage = async ctx => {
    let page = ctx.request.body.page;
    let [{
        count
    }] = await userModel.findAllPostCount()
    await userModel.findPostByPage(page)
        .then(result => {
            ctx.body = {
                result: result,
                count: count
            }
        }).catch(() => {
            ctx.body = {
                code: 500,
                message: 'error'
            }
        })
}
/**
 * 个人文章分页， 每次输出10条
 */
exports.postSelfPage = async ctx => {
    let data = ctx.request.body
    let [{
        count
    }] = await userModel.findPostCountById(data.uid)
    await userModel.findPostByUserPage(data.uid, data.page)
        .then(result => {
            ctx.body = {
                result: result,
                count: count
            }
        }).catch(() => {
            ctx.body = {
                code: 500,
                message: 'error'
            }
        })
}
/**
 * 单篇文章页
 */
exports.getSinglePosts = async ctx => {
    let postId = ctx.request.body.id,
        count,
        res,
        pageOne;
    await userModel.findDataById(postId)
        .then(result => {
            res = result
        })
        .catch(() => {
            ctx.body = {
                code: 500,
                message: 'error'
            }
        })
    await userModel.updatePostPv(postId)
    await userModel.findCommentByPage(1, postId)
        .then(result => {
            pageOne = result
        })
        .catch(() => {
            ctx.body = {
                code: 500,
                message: 'error'
            }
        })
    await userModel.findCommentCountById(postId)
        .then(result => {
            count = result[0].count
            ctx.body = {
                posts: res[0],
                commentLength: count,
                commentPageLength: Math.ceil(count / 10),
                pageOne: pageOne
            }
        })
        .catch(() => {
            ctx.body = {
                code: 500,
                message: 'error'
            }
        })

}
/**
 * 发表文章
 */
exports.postCreate = async ctx => {
    try {
        let {
            title,
            content,
            name,
            id
        } = ctx.request.body,
            time = moment().format('YYYY-MM-DD HH:mm:ss'),
            avator
        await userModel.findUserData(id)
            .then(res => {
                avator = res[0]['avator']
            })
        // await userModel.insertPost([name, title, md.render(content), content, id, time, avator])
        //第一个content是html5，第二个content是markdown
        // 下面两个content都是传过来的content为md
        await userModel.insertPost([name, title, content, content, id, time, avator])
            .then(() => {
                ctx.body = {
                    code: 200,
                    message: '发表文章成功'
                }
            }).catch(() => {
                ctx.body = {
                    code: 500,
                    message: '发表文章失败'
                }
            })
    } catch (err) {
        console.log(err)
    }
}
/**
 * 发表评论
 */
exports.postComment = async ctx => {
    let {
        user,
        uid,
        content,
        postId
    } = ctx.request.body,
        time = moment().format('YYYY-MM-DD HH:mm:ss'),
        avator;
    await userModel.findUserData(uid)
        .then(res => {
            avator = res[0]['avator']
        })
    console.log(content)
    await userModel.insertComment([user, content, time, postId, avator, uid])
    await userModel.addPostCommentCount(postId)
        .then(() => {
            ctx.body = {
                code: 200,
                message: '评论成功'
            }
        }).catch(() => {
            ctx.body = {
                code: 500,
                message: '评论失败'
            }
        })
}
/**
 * post 编辑单篇文章
 */
exports.postEditPage = async ctx => {
    let title = ctx.request.body.title,
        content = ctx.request.body.content,
        id = ctx.request.body.id,
        postId = ctx.request.body.postId,
        allowEdit = true
    // 现在使用markdown不需要单独转义
    // newTitle = title.replace(/[<">']/g, (target) => {
    //     return {
    //         '<': '&lt;',
    //         '"': '&quot;',
    //         '>': '&gt;',
    //         "'": '&#39;'
    //     } [target]
    // }),
    // newContent = content.replace(/[<">']/g, (target) => {
    //     return {
    //         '<': '&lt;',
    //         '"': '&quot;',
    //         '>': '&gt;',
    //         "'": '&#39;'
    //     } [target]
    // });
    await userModel.findDataById(postId)
        .then(res => {
            if (res[0].uid != id) {
                allowEdit = false
            } else {
                allowEdit = true
            }
        })
    if (allowEdit) {
        await userModel.updatePost([title, content, content, postId])
            .then(() => {
                ctx.body = {
                    code: 200,
                    message: '编辑成功'
                }
            }).catch(() => {
                ctx.body = {
                    code: 500,
                    message: '编辑失败'
                }
            })
    } else {
        ctx.body = {
            code: 404,
            message: '无权限'
        }
    }
}
/**
 * 删除单篇文章
 */
exports.postDeletePost = async ctx => {
    let postId = ctx.params.postId,
        allow;
    await userModel.findDataById(postId)
        .then(res => {
            if (res[0].name != ctx.session.user) {
                allow = false
            } else {
                allow = true
            }
        })
    if (allow) {
        await userModel.deleteAllPostComment(postId)
        await userModel.deletePost(postId)
            .then(() => {
                ctx.body = {
                    code: 200,
                    message: '删除文章成功'
                }
            }).catch(() => {
                ctx.body = {
                    code: 500,
                    message: '删除文章失败'
                }
            })
    } else {
        ctx.body = {
            code: 404,
            message: '无权限'
        }
    }
}
/**
 * 删除评论
 */
exports.postDeleteComment = async ctx => {
    let {
        postId,
        commentId
    } = ctx.request.body,
        allow;
    try {
        await userModel.findComment(commentId)
            .then(res => {
                console.log(ctx.state.user)
                console.log(res)
                if (res[0].name != ctx.state.user.username) {
                    allow = false
                } else {
                    allow = true
                }
            })
        if (allow) {
            await userModel.reducePostCommentCount(postId)
            await userModel.deleteComment(commentId)
                .then(() => {
                    ctx.body = {
                        code: 200,
                        message: '删除评论成功'
                    }
                }).catch(() => {
                    ctx.body = {
                        code: 500,
                        message: '删除评论失败'
                    }

                })
        } else {
            ctx.body = {
                code: 401,
                message: '无权限'
            }
        }
    } catch {
        ctx.body = {
            code: 400,
            message: '出现了点错误'
        }
    }

}
/**
 * 评论分页
 */
exports.postCommentPage = async function(ctx) {
    let postId = ctx.request.body.postId,
        page = ctx.request.body.page;
    await userModel.findCommentByPage(page, postId)
        .then(res => {
            ctx.body = res
        }).catch(() => {
            ctx.body = 'error'
        })
}